//////////////////////////////////////////////////////////////////////////////////////////
// NAME: ViewLog.java								            						//
// AUTHOR: CDT Peter Lofreddo															//
// LAST MODIFIED: 01 February 2012														//
// DESCRIPTION: Contains methods for creating, viewing and appending log files for 		//
// Nullwall																				//
// LIMITATIONS: 																		//
// CITATIONS: Inside Individual Methods.												//
//																						//
////////////////////////////////////////////////////////////////////////////////////////// 
package com.IPR2.viewlog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

public class ViewLog extends Activity {
	private TextView tv;
	private static final String TAG = "MEDIA";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tv = (TextView) findViewById(R.id.TextView01);
		checkExternalMedia();
		ListAllInstalledPrograms();
		// ReadFileFromResRaw();
		//AppendLogFile("Facebook");
		//AppendLogFile("Pandora");
		//AppendLogFile("Angry Birds");
		//AppendLogFile("Weatherbug");
		//ReadLogFile(); // Simplified for this IPR. Will add functionality later.
		//SearchLogFile("peter", true);
		//ClearLogFile();
		//ReadLogFile();
	}

	public void ListAllInstalledPrograms()
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ListAllInstalledPrograms()					            						//
		// AUTHOR: CDT Peter Lofreddo															//
		// LAST MODIFIED: 01 February 2012														//
		// DESCRIPTION: Lists package names installed on Android Device					 		//
		// LIMITATIONS: 																		//
		// CITATIONS:http://stackoverflow.com/questions/2695746/								//
		// how-to-get-a-list-of-installed-android-applications-and-pick-one-to-run 				//
		//																						//
		////////////////////////////////////////////////////////////////////////////////////////// 
	{
		final PackageManager pm = getPackageManager(); 
		//get a list of installed apps. 
		        List<ApplicationInfo> packages = pm 
		                .getInstalledApplications(PackageManager.GET_META_DATA); 
		 
		        for (ApplicationInfo packageInfo : packages) 
		        { 
		            tv.append("Installed package :" + packageInfo.packageName + "\n");  
		        }
    } 

	public void checkExternalMedia() {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: checkExternalMedia() 															//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 29 January 2012 														//
		// DESCRIPTION: Determines whether external media is available and						//
		// writable. 																			//
		// Useful for making sure USB Storage Mode is disabled and file can be					//
		// written 																				//
		// CITATIONS: Copied from																//
		// http://eagle.phys.utk.edu/guidry/android/writeSD.html 								//
		// 																						//
		// ///////////////////////////////////////////////////////////////////////////////////////
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// Can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// Can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Can't read or write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		tv.append("\n\nExternal Media: readable=" + mExternalStorageAvailable
				+ " writable=" + mExternalStorageWriteable);
	}

	public void ReadLocalResourceFile() {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ReadFileFromResRaw() 															//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 29 January 2012 														//
		// DESCRIPTION: Reads a file from Res/Raw directory of application.						//
		// Directory is READONLY 																//
		// LIMITATIONS: Does not read all files on the filesystem. 								//
		// CITATIONS: Adapted from																//
		// http://eagle.phys.utk.edu/guidry/android/writeSD.html 								//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		tv.append("\nData read from res/raw/textfile.txt:");
		InputStream is = this.getResources().openRawResource(R.raw.textfile);
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(new InputStreamReader(this
				.getResources().openRawResource(R.raw.textfile)), 8192); 
		try {
			String test;
			while (true) {
				test = br.readLine();
				// readLine() returns null if no more lines in the file
				if (test == null)
					break;
				tv.append("\n" + "    " + test);
			}
			isr.close();
			is.close();
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		tv.append("\n\n EOF");
	}

	public void CreateLogFile()
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: CreateLogFile() 																//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 01 February 2012 														//
		// DESCRIPTION: Creates a blank log file. This method is not needed to use				//
		// 																						//
		// AppendLogFile(String sBody). It has been added to provide clarity an					//
		// intuitive codebase 																	//
		// does not need CreateLogFile() to first append to file; Used for clarity				//
		// 																						//
		// CITATIONS: Adapted from http://stackoverflow.com/questions/4580683/ 					//
		// android-java-writing-text-file-to-sd-card 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
	{
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			tv.append("\nLog File Created In Directory: " + root);
			File gpxfile = new File(root, "Nullwall_Log.txt");
			FileWriter writer = new FileWriter(gpxfile, true);
			writer.write("");
			writer.flush();
			writer.close();
			Toast.makeText(this, "Log Successfully Created!",
					Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			tv.append(" \n File not Saved! CreateLogFile() Broken!");
		}
	}

	public void AppendLogFile(String sBody) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: AppendLogFile(sBody) 															//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 01 February 2012 														//
		// DESCRIPTION: Adds text to the log file located at									//
		// mnt/sdcard/Nullwall. AppendLogFile(sBody) 											//
		// does not need CreateLogFile() to first append to file; Used for						//
		// clarity 																				//
		// CITATIONS: Adapted from http://stackoverflow.com/questions/4580683/					//
		// android-java-writing-text-file-to-sd-card 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			tv.append("\nLog File Created In Directory: " + root);
			File gpxfile = new File(root, "Nullwall_Log.txt");
			FileWriter writer = new FileWriter(gpxfile, true);
			writer.write(sBody + "\n");
			writer.flush();
			writer.close();
			Toast.makeText(this, "Log Successfully Created!",
					Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			tv.append(" \n File not Saved! CreateLogFile() Broken!");
		}
	}

	public void ReadLogFile() {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ReadLogFile() 																	//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 01 February 2012 														//
		// DESCRIPTION: Views file from mnt/sdcard/Nullwall_Logfiles 							//
		// CITATIONS: Adapted from http://www.anddev.org/read_a_txt_file_ 						//
		// from_sd_card_in_a_real_device-t6619.html 											//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Nullwall/" + "Nullwall_Log.txt");
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			String readString = new String();
			tv.append(" \n\n Reading File Recently Created: \n");

			// just reading each line and pass it on the debugger
			while ((readString = buf.readLine()) != null) {
				tv.append(readString + "\n");

			}

		} catch (FileNotFoundException e) {
			tv.append(" \n File not Found! ViewFile() Broken!");
			e.printStackTrace();

		} catch (IOException e) {
			tv.append(" \n IOException! ViewFile() Broken!");
			e.printStackTrace();

		}
	}

	public void ClearLogFile() {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: ClearLog() 																	//
		// AUTHOR: CDT Peter Lofreddo 															//
		// LAST MODIFIED: 31 January 2012 														//
		// DESCRIPTION: Clears file from mnt/sdcard/Nullwall_Logfiles. Does not					//
		// Delete File. 																		//
		// CITATIONS: 																			//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		try {
			File root = new File(Environment.getExternalStorageDirectory(),
					"Nullwall");
			if (!root.exists()) {
				root.mkdirs();
			}
			File gpxfile = new File(root, "Nullwall_Log.txt");
			FileWriter writer = new FileWriter(gpxfile, false);
			writer.write("");
			writer.flush();
			writer.close();
		} catch (FileNotFoundException e) {
			tv.append(" \n File not Found! ClearLog() Broken!");
			e.printStackTrace();

		} catch (IOException e) {
			tv.append(" \n IOException! ClearLog() Broken!");
			e.printStackTrace();
		}
	}

	public boolean SearchLogFile(String searchString, Boolean caseSensitive) {
		//////////////////////////////////////////////////////////////////////////////////////////
		// NAME: SearchLogFile(String searchString,Boolean caseSensitive) 						//
		// AUTHOR: CDT Peter Lofreddo															//
		// LAST MODIFIED: 01 February 2012 														//
		// DESCRIPTION: Searches for string in log file. caseSensitive = true					//
		// for Case sensitive 																	//
		// searching, choose false to ignore case 												//
		// CITATIONS: Adapted																	//
		// From http://stackoverflow.com/questions/5912753/java-find-and-replace-text			//
		// 																						//
		//////////////////////////////////////////////////////////////////////////////////////////
		boolean unfound = true;
		try {
			File f = new File(Environment.getExternalStorageDirectory()
					+ "/Nullwall/" + "Nullwall_Log.txt");
			FileInputStream fileIS = new FileInputStream(f);
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					fileIS));
			String line;
			while ((line = buf.readLine()) != null) {
				line = buf.readLine();
				if (caseSensitive) {
					if (line.equals(searchString)) {
						unfound = false;
						tv.append("You found it! case sensitive");
					}
				} else if (line.equalsIgnoreCase(searchString)) {
					unfound = false;
					tv.append("You found it! not case sensitive");
				}
			}
			if (unfound) {
				tv.append("You did not find " + searchString
						+ " in the log file \n");
			}
			return unfound;
		} catch (FileNotFoundException e) {
			tv.append(" \n File not Found! SearchLogFile(searchString) Broken!");
			e.printStackTrace();
			return true;

		} catch (IOException e) {
			tv.append(" \n IOException! SearchLogFile(searchString) Broken!");
			e.printStackTrace();
			return true;
		}
	}
}
